<template>
  <a-modal
    v-model="showModal"
    width="860px"
    title="对服务商订单进行结算"
    :ok-text="step === 0 ? '下一步' : '提交结算'"
    :confirm-loading="loading"
    @ok="submit"
  >
    <a-spin :spinning="loading" :tip="step === 0 ? undefined : '结算中...'">
      <section style="padding-right: 8px; height: calc(100vh - 448px); overflow: auto">
        <a-steps style="width: 80%" class="m-auto mb-24" v-model="step">
          <a-step title="填写结算信息"></a-step>
          <a-step disabled title="确认结算额度"></a-step>
        </a-steps>
        <section class="top-info mb-16" v-show="step === 1">
          <section class="item">
            <section class="label">服务商名称</section>
            <section class="value primary-color">{{ settleInfo.vendorName }}</section>
          </section>
          <section class="item">
            <section class="label font-bold text-16" style="color: #333">本次结算金额</section>
            <section class="value primary-color font-bold text-20">{{ settleInfo.settledAmount }}元</section>
          </section>
          <section class="item">
            <section class="label">服务商账户余额</section>
            <section class="value primary-color">{{ settleInfo.vendorAmount }}元</section>
          </section>
        </section>
        <a-alert style="width: 90%" class="m-auto" type="info" show-icon message="只有已还车的已完成订单可以结算" />
        <a-form v-show="step === 0" style="width: 80%" :form="form" class="inline-form m-auto mt-24">
          <a-form-item label="结算服务商">
            <a-select
              allow-clear
              show-search
              labelInValue
              :filter-option="filterOption"
              class="w-full"
              placeholder="请选择结算服务商"
              :loading="selectConfig.searchLoading"
              @focus="focus"
             @search="searchData"
             @popupScroll="scroll"
              :disabled="!!vendorId"
              v-decorator="['vendorId', { rules: [{ required: true, message: '请选择结算服务商' }] }]"
            >
              <a-select-option v-for="item in vendorList" :value="item.id" :key="item.id">{{
                item.name
              }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="结算起始日期">
            <a-date-picker
              class="w-full"
              placeholder="请选择结算起始日期"
              v-decorator="['startDateTime', { rules: [{ required: true, message: '请选择结算起始日期' }] }]"
            ></a-date-picker>
          </a-form-item>
          <a-form-item label="结算截至日期">
            <a-date-picker
              class="w-full"
              placeholder="请选择结算截至日期"
              v-decorator="['endDateTime', { rules: [{ required: true, message: '请选择结算截至日期' }] }]"
            ></a-date-picker>
          </a-form-item>
        </a-form>
        <a-table class="mt-16" v-show="step === 1" :columns="columns" :data-source="data" :pagination="pagination">
          <template #commissionAmount="val, data"> {{ val }}元 </template>
        </a-table>
      </section>
    </a-spin>
  </a-modal>
</template>
<script>
import { getVendorSettleInfo, getVendorToBeSettleOrderPage, settleVendorOrder } from '@/api/order/settlement'
import { getAllVendors } from '@/api/vendor'
import { tableMixins } from '@/utils/mixins'
import { searchVendor} from '@/api/vendor'
import { debounce} from 'lodash'
export default {
  name: 'Settlement',
  mixins: [tableMixins],
  props: {
    vendorId: {
      type: [Number, String],
      default: '',
    },
  },
  data() {
    return {
      loading: false,
      showModal: false,
      step: 0,
      rowsNum: 5,
      form: this.$form.createForm(this),
      formData: {},
      settleInfo: {},
      vendorList: [],
      columns: [
        { dataIndex: 'orderId', title: '订单号', align: 'center' },
        { dataIndex: 'createTime', title: '下单时间', align: 'center' },
        { dataIndex: 'totalActualFee', title: '订单金额', align: 'center' },
        {
          dataIndex: 'commissionAmount',
          title: '结算金额',
          scopedSlots: { customRender: 'commissionAmount' },
          align: 'center',
        },
        { dataIndex: 'channelName', title: '来源渠道', align: 'center' },
      ],
      pageSizeOptions: ['5', '10', '20', '40'],
      data: [],
      selectConfig:{
        searchKey: '',
        searchLoading: false,
        data: [],
        total:0,
        pageNum:1,
        rowsNum:10,
      }
    }
  },
  watch: {
    showModal() {
      this.step = 0
      this.form.resetFields()
      this.formData = {}
    },
  },
  created() {
    // searchVendor().then((data) => (this.vendorList = data))
    this.searchData = debounce(this.searchData, 1000);
  },
  methods: {
    getVendorList(){
      this.selectConfig.searchLoading = true
      searchVendor({
            search: this.selectConfig.searchKey.trim(),
            rowsNum: this.selectConfig.rowsNum,
           pageNum: this.selectConfig.pageNum,
            isEnabled: true
          }).then((data) => {
            this.selectConfig.searchLoading = false
            const {items, rowCount} = data
           this.vendorList = this.selectConfig.pageNum === 1 ? items : this.vendorList.concat(items)
           this.selectConfig.total = rowCount
          }
        ).catch(() => this.selectConfig.searchLoading = false)
    },
    searchData(searchKey) {
        this.selectConfig.searchKey = searchKey
        this.selectConfig.pageNum = 1
        this.getVendorList()
      },
    focus() {
        this.selectConfig.searchKey = ''
        this.selectConfig.pageNum = 1
        this.getVendorList()
      },
    // scroll(e){
    //     const {scrollHeight, scrollTop, clientHeight} = e.target
    //     console.log(scrollHeight - scrollTop === clientHeight);
    //     // if (scrollHeight - scrollTop === clientHeight) {
    //     //   if (this.vendorList.length === this.selectConfig.total) return
    //     //   this.selectConfig.pageNum++
    //     //   this.getVendorList()
    //     // }
    //   },
      scroll:debounce (function (e) {
        const {scrollHeight, scrollTop, clientHeight} = e.target
        if (scrollHeight - scrollTop === clientHeight) {
          if (!(this.vendorList.length === this.selectConfig.total)){
            this.selectConfig.pageNum++
            this.getVendorList()
          }
          
        }
      },500),
      
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    open() {
      this.showModal = true
      if (this.vendorId) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            vendorId: Number(this.vendorId),
          })
        })
      }
    },
    getData() {
      this.loading = true
      return getVendorToBeSettleOrderPage({
        pageNo: this.pageNum,
        pageSize: this.rowsNum,
        vendorId: this.formData.vendorId,
        startDateTime: this.formData.startDateTime,
        endDateTime: this.formData.endDateTime,
      })
        .then((data) => {
          this.data = data.items
          this.total = data.rowCount
        })
        .finally(() => (this.loading = false))
    },
    submit() {
    
      if (this.step === 0) {
        this.form.validateFields(async (err, values) => {
          if (!err) {
            let obj={...values,vendorId:values.vendorId.key}
            this.formData = obj
            this.loading = true
            await getVendorSettleInfo(obj)
              .then((data) => {
                this.settleInfo = data
              })
              .then(async () => {
                await this.getData()
                this.step = 1
              })
              .finally(() => (this.loading = false))
          }
        })
      } else {
        this.loading = true
        settleVendorOrder(this.formData)
          .then(() => {
            this.$message.success('提交成功！')
            this.showModal = false
            this.$emit('success')
          })
          .finally(() => (this.loading = false))
      }
    },
  },
}
</script>
<style scoped lang="less">
.inline-form /deep/ .ant-form-item-label {
  width: 110px;
  text-align: right;
}
.top-info {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .item {
    margin: 0 20px;
    text-align: center;
    .label {
      margin-bottom: 8px;
      color: #999;
    }
    .value {
    }
  }
}
</style>
